import React from 'react';
import ImageLazy from '../commons/ImageLazy';
import NavLink from '../commons/NavLink';
import { connect } from 'react-redux';
import {hashHistory } from 'react-router'
import {get_add_shopcar,checkArr,dele_shop_order} from '../../actions';
import {getHosImg,getDocImg,getServImg} from '../../actions/ActionTypes';
import 'whatwg-fetch';

const user_dele = require('!url?limit=8192&name=static/img/[hash:6].[ext]!../../static/img/user_dele.png');
const duihao = require('!url?limit=8192&name=static/img/[hash:6].[ext]!../../static/img/duihao.png');


let mydefault = React.createClass({
  componentDidMount:function(){
    const {dispatch} = this.props;

    //获取购物车清单
    dispatch(get_add_shopcar(this.props.userId))
    let _this =this;
    //选中
    // $('.item_wrapper ').each(function(){
      $('.item_wrapper ').on('click','.item .checks',function(){
        if(!$(this).data('checked')){
          $(this).addClass('active')
        }else{
          $(this).removeClass('active')
        }
        $(this).data('checked',!$(this).data('checked'));
        _this.get_total();
      })
    // })

    // 全选/全不选
    $('.fix_total .top span').eq(0).on('click',function(){
      // console.log(!$(this).data('checked'))
      if(!$(this).data('checked')){
        $(this).addClass('active')
        $(this).data('checked','true');
        $('.item_wrapper em.checks').each(function(){
          $(this).addClass('active')
          $(this).data('checked','true');
        })
      }else{
        $(this).removeClass('active')
        $(this).data('checked','false');
        $('.item_wrapper em.checks').each(function(){
          $(this).removeClass('active')
          $(this).data('checked','false');
        })
      }
      _this.get_total();
    })
    //结算
    $('.fix_total a').eq(0).click(function(){
      let this_status_active_length = $('.item_wrapper em.checks.active').length;
      let arr = [];
      $('.item_wrapper em.checks.active').each(function(){
        arr.push($(this).attr('data-key'));
      });
      if(this_status_active_length <= 0){
        alert('请至少选择一项结算');
        return false;
      }else{
        dispatch(checkArr(arr))
        hashHistory.push("/user/confirm_order")
      }
    })

    //如果用户曾选中 默认重现选中的订单
      // _this.props.checkedArr.forEach(function(item){
      //   $('.item_wrapper em.checks').eq(item).trigger('click')
      // })
    this.addCtr();
      //删除
      let that = this;
      $('.item_wrapper').on('click','.dele',function(){
        let sure = confirm('您确定要删除此项商品吗');
        let this_ = $(this);
        let _this = $(this).parents('.item');
        let o_h = _this.height();
        // console.log(o_h);
        if(sure){
          _this.css('height',o_h).animate({
            height:"0",
            opacity:0
          },300,function(){
            _this.remove();
            var cartId = this_.parents('.ctr').attr('data-cartId');
              dispatch(dele_shop_order(cartId,function(){
                dispatch(get_add_shopcar(that.props.userId))
              }))
          })
        }
      })
  },
  componentDidUpdate:function(){
    this.addCtr();
    const {dispatch} = this.props;
      let _this = this;



  },
  addCtr:function(){
    let that = this;
    $('.ctr').each(function(){
      let o_num = $(this).find('var').text();
      let _this = $(this);
      $(this).find('.minus').tap(function(){
        if(o_num>1){
          _this.find('var').text(--o_num)
        }else{
          return false;
        }

      })
      $(this).find('.add').tap(function(){
        _this.find('var').text(++o_num)
      })
      $(this).find('.add,.minus').tap(function(){
        var cartId = $(this).parents('.ctr').attr('data-cartId'),
            itemNum = $(this).parent().find('var').text();
        const query = `cart_id=${cartId}&item_num=${itemNum}`
          fetch("http://120.27.37.54/mall/cart/modify-num", {
            method: "POST",
            headers: {
              "Content-Type": "application/x-www-form-urlencoded"
            },
            body: query
          }).then(function(res) {
            if (res.ok) {
              that.get_total();
              console.log("success");
            } else if (res.status == 401) {
              console.log("Oops! You are not authorized.");
            }
          }, function(e) {
            console.log("Error submitting form!");
          });
      })
    })
  },
  get_total:function(){
    this.props.total = 0;
    let that= this;
    $('.item_wrapper .item').each(function(){
      if($(this).find('.checks.active').length != 0){
        that.props.total += $(this).find('.price').text() * $(this).find('.ctr var').text();
      }
    })
    $('.fix_total .total_price').text(that.props.total)
  },
  render:function(){
    let user_shop_list = this.props.user_shop_list || [];
    let _this = this;
    // console.log(user_shop_list)
    return(
      <div className="u_shop_car hasCheck">
        <div className="item_wrapper">
          {
            user_shop_list.map(function(item,index){
              _this.props.total += item.price*item.itemNum;
              let imgSrc = getServImg(item.itemImage,'_200_200',item.hospitalId,item.itemId)
              return(
                <div className="item border_b1">
                  <div className="wrapper clearfix">
                    <em className="checks" data-key={index} data-checked="false"><var></var></em>
                    <h4>{item.itemName}·{item.itemClass}·{item.doctorName}{item.doctorTitle}</h4>
                    <div className="mid">
                      {/* <ImageLazy src={imgSrc} style={{height:"1.2rem"}}  /> */}
                      <em style={{"background-image":"url("+ imgSrc + ")"}}></em>
                      <div>
                        医院：{item.hospitalName}<br/><br/>
                        包含：{item.itemName}
                      </div>
                    </div>
                    <h5>预约金：¥ <font className="price">{item.price}</font></h5>
                    <div className="ctr" data-cartId={item.cartId}>
                      <span><em className="minus iconfont"></em><var>{item.itemNum}</var><em className="add">+</em></span>
                      <a href="javascript:void(0)" className="dele"><img src={user_dele} style={{height:".3rem"}} /></a>
                    </div>
                  </div>
                </div>
              )
            })
          }
        </div>
        <div className="fix_total border_t1 box">
          <div className="top">
            <span><em></em>全选</span>
            <span><var></var>合计：¥ <font className="total_price">{this.props.total}</font></span>
          </div>
          <a href="javascript:void(0)">结算</a>
        </div>
      </div>
    )
  }
})

let mapStateToProps = (state) => {
  var userId = state.user.userId || 0,
      total = 0,
      user_shop_list = state.user.user_shop_list || [],
      checkedArr = state.user.checkedArr || [];
      // console.log(state.user)
  return{
    userId,
    total,
    checkedArr,
    user_shop_list
  }
}

export default connect(mapStateToProps)(mydefault);
